<template>
  <div>
    <div style="border: 2px solid #000;">
      <h5>测试computed:</h5>
      <h5>num:{{ num }}</h5>
      <h5>numComputed:{{ numadd }}</h5>
      <button @click="addNum">num++</button>
    </div>
    <div>
      <h5>测试watch：</h5>
      <h5>监听基本类型name: {{ name }}</h5>
      <h5>监听复杂类型age: {{ objValue.age }}</h5>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
// computed
const num = ref(1)
const addNum = () => {
  num.value++
}
const numadd = computed(() => {
  return num.value * 2
})
// watch
// 监听简单类型
const name = ref('lily')
const timerout = setTimeout(() => {
  name.value = 'pipi'
  clearTimeout(timerout)
}, 1000)
watch(name, (newvalue, oldvalue) => {
  console.log('name', newvalue, oldvalue)
}, { immediate: true }) // 立即执行（使用immediate页面加载就会执行一次）
// 监听复杂类型
const objValue = reactive({ age: 21, name: 'yanyan' })
const timeAge = setTimeout(() => {
  objValue.age++
  clearTimeout(timeAge)
}, 2000)
watch(() => objValue, (newValue, oldValue) => {
  console.log('objValue', newValue, oldValue)
}, { deep: true }) // 想要监听整个对象的变化必须使用deep，如果监听对象中某个属性的变化则不需要
watch(() => objValue.age, (newValue, oldValue) => { // 监听对象中摸个属性的变化
  console.log('objValue.age', newValue, oldValue)
})
// 监听多个属性
const timeName = setTimeout(() => {
  objValue.name = 'nannan'
  clearTimeout(timeName)
}, 3000)
watch([name, () => objValue.name], (newName, oldName) => {
  console.log('触发：', newName, oldName) // 返回的是两个数组，第一个参数是新值组成的数组，第二个是旧值组成的数组
})

</script>

<style>
</style>
